<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Models\Role;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class RoleService
{
    public function get($search,$parent_id,$type = 'company'){
        $sql = Role::select('id','name','status','auth','created_at','parent_id')->with('parent')->with('roles')->with('users')->when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('name','like', '%'.$search.'%');
            });
        })
        ->when($parent_id, function ($query, $parent_id) {
            return $query->where(function($query) use ($parent_id) {
                $query->where('parent_id',$parent_id);
            });
        });

        if($type == 'company'){
            $sql->where('company_id',Auth::user()->company_id);
        }
        return $sql;
    }

    public function insert($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        try {
            $res['auth'] = json_encode($res['auth']);
            $res['status'] = $res['status'] ? 1 : 0;
            $res['company_id'] = Auth::user()->company_id;
            $data = Role::create($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th->getMessage()));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $res['auth'] = json_encode($res['auth']);
            $res['status'] = $res['status'] ? 1 : 0;
            $data = Role::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function status($data){
        try {
            $data->status =  $data->status ? 0 : 1;
            $data->save();
            if($data->id){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
}